package com.bjpowernode.seckillweb.controller;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.Goods;
import com.bjpowernode.entity.Orders;
import com.bjpowernode.entity.Users;
import com.bjpowernode.seckillweb.service.GoodsService;
import com.bjpowernode.seckillweb.service.impl.LuaService;
import com.bjpowernode.vo.HttpResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 秒杀controller
 */

@RestController
public class SpikeController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private LuaService luaService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ObjectMapper objectMapper;

    @PostMapping("/goods/{id}/{random}")
    public HttpResult doSpike(@PathVariable("id") Integer id, @PathVariable("random") String random, HttpServletRequest request) throws JsonProcessingException {
        //查询秒杀的商品
        Goods goods = (Goods)redisTemplate.opsForValue().get(Constants.REDIS_GOODS + id);

        //判断随机码是否正确
        if (!goods.getRandomName().equals(random)) {
            return HttpResult.builder().code(Constants.ERROR).msg("不合法").build();
        }

        //判断秒杀是否进行中
        long currentTime = System.currentTimeMillis();

        long startTime = goods.getStartTime().getTime();
        long endTime = goods.getEndTime().getTime();

        if (currentTime < startTime) {
            return HttpResult.builder().code(Constants.ERROR).msg("秒杀未开始").build();
        }
        if (currentTime > endTime) {
            return HttpResult.builder().code(Constants.ERROR).msg("秒杀已结束").build();
        }

        //获取用户登录信息  从session中获取
        Users user = (Users) request.getSession().getAttribute(Constants.LOGIN_USER);

        //执行lua脚本
        Long luaResult = luaService.runLua(id, user.getId());

        //判断lua脚本的返回值
        if (luaResult == -1) {
            return HttpResult.builder().code(Constants.ERROR).msg("您已秒杀过该商品，不能重复秒杀").build();
        }

        if (luaResult == -2) {
            return HttpResult.builder().code(Constants.ERROR).msg("服务器太拥挤，请稍后再试").build();
        }

        if (luaResult == -3) {
            return HttpResult.builder().code(Constants.ERROR).msg("商品售罄").build();
        }

        //向mq中发送订单消息
        Orders orders = Orders.builder()
                .uid(user.getId())
                .createTime(new Date())
                .orderMoney(goods.getPrice())
                .goodsId(goods.getId())
                .buyNum(1)
                .buyPrice(goods.getPrice())
                .status(0) //订单状态  0 待支付
                .build();



        //将order转成json
        String orderStr = objectMapper.writeValueAsString(orders);

        //将json数据放入message中
        Message message = MessageBuilder.withBody(orderStr.getBytes()).build();

        //向mq发送消息
        rabbitTemplate.convertAndSend(Constants.EXCHANGE_NAME_ORDER, Constants.ROUTING_KEY_ORDER, message);

        return HttpResult.builder().code(Constants.SUCCESS).msg("正在秒杀，请稍后查询结果").build();
    }
}
